<template>
  <div class="debug-page">
    <div class="debug-header">
      <h1>🔧 页面调试工具</h1>
      <p>诊断页面不显示的问题</p>
    </div>

    <div class="debug-content">
      <!-- 系统状态 -->
      <div class="debug-section">
        <h2>📊 系统状态</h2>
        <div class="status-grid">
          <div class="status-card">
            <div class="status-icon">🌐</div>
            <div class="status-content">
              <div class="status-title">前端服务</div>
              <div class="status-value" :class="frontendStatus.class">
                {{ frontendStatus.text }}
              </div>
            </div>
          </div>
          <div class="status-card">
            <div class="status-icon">🔧</div>
            <div class="status-content">
              <div class="status-title">后端服务</div>
              <div class="status-value" :class="backendStatus.class">
                {{ backendStatus.text }}
              </div>
            </div>
          </div>
          <div class="status-card">
            <div class="status-icon">🔑</div>
            <div class="status-content">
              <div class="status-title">认证状态</div>
              <div class="status-value" :class="authStatus.class">
                {{ authStatus.text }}
              </div>
            </div>
          </div>
          <div class="status-card">
            <div class="status-icon">🛣️</div>
            <div class="status-content">
              <div class="status-title">当前路由</div>
              <div class="status-value">{{ currentRoute }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 路由信息 -->
      <div class="debug-section">
        <h2>🛣️ 路由信息</h2>
        <div class="route-info">
          <div class="info-item">
            <strong>当前路径:</strong> {{ $route.path }}
          </div>
          <div class="info-item">
            <strong>路由名称:</strong> {{ $route.name }}
          </div>
          <div class="info-item">
            <strong>路由参数:</strong> {{ JSON.stringify($route.params) }}
          </div>
          <div class="info-item">
            <strong>查询参数:</strong> {{ JSON.stringify($route.query) }}
          </div>
          <div class="info-item">
            <strong>路由元信息:</strong> {{ JSON.stringify($route.meta) }}
          </div>
        </div>
      </div>

      <!-- 认证信息 -->
      <div class="debug-section">
        <h2>🔑 认证信息</h2>
        <div class="auth-info">
          <div class="info-item">
            <strong>用户Token:</strong> {{ userToken || '无' }}
          </div>
          <div class="info-item">
            <strong>管理员Token:</strong> {{ adminToken || '无' }}
          </div>
          <div class="info-item">
            <strong>用户类型:</strong> {{ userType || '无' }}
          </div>
          <div class="info-item">
            <strong>用户信息:</strong> {{ userInfo || '无' }}
          </div>
        </div>
        <div class="auth-actions">
          <el-button @click="setTestToken" type="primary">设置测试Token</el-button>
          <el-button @click="clearAuth" type="danger">清除认证</el-button>
          <el-button @click="goToHome" type="success">跳转到首页</el-button>
        </div>
      </div>

      <!-- 组件状态 -->
      <div class="debug-section">
        <h2>🧩 组件状态</h2>
        <div class="component-info">
          <div class="info-item">
            <strong>App组件:</strong> {{ appComponentStatus }}
          </div>
          <div class="info-item">
            <strong>AppLayout组件:</strong> {{ appLayoutStatus }}
          </div>
          <div class="info-item">
            <strong>RouterView:</strong> {{ routerViewStatus }}
          </div>
        </div>
      </div>

      <!-- 错误日志 -->
      <div class="debug-section">
        <h2>📝 错误日志</h2>
        <div class="error-logs">
          <div v-for="log in errorLogs" :key="log.id" class="log-item" :class="log.level">
            <span class="log-time">{{ log.time }}</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
        <el-button @click="clearLogs" size="small">清除日志</el-button>
      </div>

      <!-- 快速操作 -->
      <div class="debug-section">
        <h2>⚡ 快速操作</h2>
        <div class="quick-actions">
          <el-button @click="refreshPage" type="primary">刷新页面</el-button>
          <el-button @click="goToLogin" type="warning">跳转到登录</el-button>
          <el-button @click="goToCategory" type="info">跳转到分类</el-button>
          <el-button @click="goToSearch" type="success">跳转到搜索</el-button>
          <el-button @click="testAPI" type="default">测试API</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElButton } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 响应式数据
const frontendStatus = reactive({ text: '检测中...', class: 'checking' })
const backendStatus = reactive({ text: '检测中...', class: 'checking' })
const authStatus = reactive({ text: '检测中...', class: 'checking' })
const currentRoute = ref('')
const userToken = ref('')
const adminToken = ref('')
const userType = ref('')
const userInfo = ref('')
const appComponentStatus = ref('正常')
const appLayoutStatus = ref('正常')
const routerViewStatus = ref('正常')
const errorLogs = ref([])

// 计算属性
const authStatusComputed = computed(() => {
  const token = userToken.value || adminToken.value
  if (token) {
    authStatus.text = '已认证'
    authStatus.class = 'success'
  } else {
    authStatus.text = '未认证'
    authStatus.class = 'error'
  }
  return authStatus
})

// 检查服务状态
const checkServices = async () => {
  // 检查前端服务
  try {
    const response = await fetch('/')
    if (response.ok) {
      frontendStatus.text = '运行中'
      frontendStatus.class = 'success'
    } else {
      frontendStatus.text = '异常'
      frontendStatus.class = 'error'
    }
  } catch (error) {
    frontendStatus.text = '无法连接'
    frontendStatus.class = 'error'
    addLog('error', '前端服务检查失败: ' + error.message)
  }

  // 检查后端服务
  try {
    const response = await fetch('http://127.0.0.1:8000/api/test')
    if (response.ok) {
      backendStatus.text = '运行中'
      backendStatus.class = 'success'
    } else {
      backendStatus.text = '异常'
      backendStatus.class = 'error'
    }
  } catch (error) {
    backendStatus.text = '无法连接'
    backendStatus.class = 'error'
    addLog('error', '后端服务检查失败: ' + error.message)
  }
}

// 检查认证状态
const checkAuth = () => {
  userToken.value = localStorage.getItem('token') || ''
  adminToken.value = localStorage.getItem('adminToken') || ''
  userType.value = localStorage.getItem('userType') || ''
  userInfo.value = localStorage.getItem('user') || localStorage.getItem('adminUser') || ''
  
  authStatusComputed.value
}

// 更新路由信息
const updateRouteInfo = () => {
  currentRoute.value = route.name || route.path
}

// 添加日志
const addLog = (level, message) => {
  errorLogs.value.unshift({
    id: Date.now(),
    time: new Date().toLocaleTimeString(),
    level,
    message
  })
  
  if (errorLogs.value.length > 50) {
    errorLogs.value = errorLogs.value.slice(0, 50)
  }
}

// 操作方法
const setTestToken = () => {
  localStorage.setItem('token', 'test-token-for-development')
  localStorage.setItem('user', JSON.stringify({ id: 1, name: '测试用户', email: 'test@example.com' }))
  checkAuth()
  addLog('success', '已设置测试Token')
}

const clearAuth = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('adminToken')
  localStorage.removeItem('userType')
  localStorage.removeItem('user')
  localStorage.removeItem('adminUser')
  checkAuth()
  addLog('info', '已清除所有认证信息')
}

const goToHome = () => {
  router.push('/home')
  addLog('info', '跳转到首页')
}

const goToLogin = () => {
  router.push('/login')
  addLog('info', '跳转到登录页')
}

const goToCategory = () => {
  router.push('/category')
  addLog('info', '跳转到分类页')
}

const goToSearch = () => {
  router.push('/search')
  addLog('info', '跳转到搜索页')
}

const refreshPage = () => {
  window.location.reload()
}

const testAPI = async () => {
  try {
    const response = await fetch('http://127.0.0.1:8000/api/test')
    const data = await response.json()
    addLog('success', 'API测试成功: ' + data.message)
  } catch (error) {
    addLog('error', 'API测试失败: ' + error.message)
  }
}

const clearLogs = () => {
  errorLogs.value = []
  addLog('info', '日志已清除')
}

// 监听路由变化
const unwatchRoute = route.watch(() => {
  updateRouteInfo()
})

// 生命周期
onMounted(() => {
  addLog('info', '调试页面已加载')
  checkServices()
  checkAuth()
  updateRouteInfo()
  
  // 监听错误
  window.addEventListener('error', (event) => {
    addLog('error', `JavaScript错误: ${event.message}`)
  })
  
  window.addEventListener('unhandledrejection', (event) => {
    addLog('error', `Promise错误: ${event.reason}`)
  })
})

onUnmounted(() => {
  unwatchRoute()
})
</script>

<style scoped>
.debug-page {
  min-height: 100vh;
  background: #f8fafc;
  padding: 20px;
}

.debug-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.debug-header h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
  font-weight: 700;
}

.debug-header p {
  font-size: 1.1rem;
  opacity: 0.9;
}

.debug-content {
  max-width: 1200px;
  margin: 0 auto;
}

.debug-section {
  background: white;
  border-radius: 15px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
}

.debug-section h2 {
  color: #1f2937;
  font-size: 1.5rem;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 3px solid #667eea;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.status-card {
  background: #f8fafc;
  border-radius: 10px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  border: 2px solid #e5e7eb;
  transition: all 0.3s ease;
}

.status-card:hover {
  border-color: #667eea;
  transform: translateY(-2px);
}

.status-icon {
  font-size: 2rem;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e0e7ff;
  border-radius: 50%;
}

.status-content {
  flex: 1;
}

.status-title {
  font-size: 0.9rem;
  color: #6b7280;
  margin-bottom: 5px;
}

.status-value {
  font-size: 1.2rem;
  font-weight: 600;
}

.status-value.success {
  color: #10b981;
}

.status-value.error {
  color: #ef4444;
}

.status-value.checking {
  color: #f59e0b;
}

.route-info,
.auth-info,
.component-info {
  background: #f9fafb;
  border-radius: 10px;
  padding: 20px;
}

.info-item {
  margin: 10px 0;
  padding: 10px;
  background: white;
  border-radius: 6px;
  border-left: 4px solid #667eea;
}

.info-item strong {
  color: #374151;
  margin-right: 10px;
}

.auth-actions,
.quick-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-top: 20px;
}

.error-logs {
  background: #1f2937;
  color: #f9fafb;
  padding: 20px;
  border-radius: 10px;
  max-height: 300px;
  overflow-y: auto;
  font-family: 'Courier New', monospace;
  font-size: 0.9rem;
  margin-bottom: 15px;
}

.log-item {
  margin: 3px 0;
  padding: 2px 0;
}

.log-time {
  color: #9ca3af;
  margin-right: 10px;
}

.log-item.info .log-message {
  color: #60a5fa;
}

.log-item.warning .log-message {
  color: #fbbf24;
}

.log-item.error .log-message {
  color: #f87171;
}

.log-item.success .log-message {
  color: #34d399;
}

@media (max-width: 768px) {
  .debug-header h1 {
    font-size: 2rem;
  }
  
  .status-grid {
    grid-template-columns: 1fr;
  }
  
  .auth-actions,
  .quick-actions {
    flex-direction: column;
  }
}
</style>
